package com.umeox.watch.moto.launcher.ui;


import static com.umeox.watch.moto.dataservice.constants.Constants.ACTION_THUMBS_UP;
import static com.umeox.watch.moto.launcher.constant.Constant.KEY_UNBIND;
import static com.umeox.watch.moto.launcher.constant.Constant.UNBIND_RESTART;
import static com.umeox.watch.moto.launcher.ui.ChallengeTriggerActivity.EXTRA_CHALLENGE_ID;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.umeox.moto.common.log.Logger;
import com.umeox.moto.common.utils.NetUtils;
import com.umeox.moto.watch.themes.app.ThemeAppCompatActivity;
import com.umeox.moto.watch.themes.dialog.MainDialogInterface;
import com.umeox.moto.watch.themes.dialog.NotificationDialog;
import com.umeox.watch.moto.dataservice.DataProvider;
import com.umeox.watch.moto.dataservice.constants.Constants;
import com.umeox.watch.moto.dataservice.proxy.PushApiClientProxy;
import com.umeox.watch.moto.launcher.R;
import com.umeox.watch.moto.launcher.adapter.HomePagerAdapter;
import com.umeox.watch.moto.launcher.event.CustomWallpaperChangedEvent;
import com.umeox.watch.moto.launcher.event.DeviceStatusChangedEvent;
import com.umeox.watch.moto.launcher.event.HorizontalScrollToPagerEvent;
import com.umeox.watch.moto.launcher.event.LocaleChangedEvent;
import com.umeox.watch.moto.launcher.event.NotificationManagerEvent;
import com.umeox.watch.moto.launcher.event.PrayerTimeListFragmentVisibleEvent;
import com.umeox.watch.moto.launcher.event.ScrollToPagerEvent;
import com.umeox.watch.moto.launcher.widget.MainTipsDialog;
import com.umeox.watch.moto.pedometer.util.CacheImpl;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.List;


public class MainActivity extends ThemeAppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    private static final int HOME_PAGE_INDEX = 1;
    private static final int BIND_HOME_PAGE_INDEX = 2;

    private int mHomePagerIndex = HOME_PAGE_INDEX;
    public static final String ACTION_BACK = "com.wherecom.intent.action.ACTION_BACK";
    public static final String ACTION_OUT_CALL_CONNETCTED = "android.intent.action.MO_CONNETCTED";
    private static final int MSG_SEND_EVEN_BUS = 0x200;
    private ViewPager2 mPager;
    private boolean mForbidPeriodNow;
    private int mCurrentPagerPosition;
    private ClassModeReceiver mClassModeReceiver = new ClassModeReceiver();
    private MainDialogInterface mClassModeDialog;
    private boolean isBind;
    private HomePagerAdapter mPagerAdapter;
    private NotificationDialog mBatteryLowDialog;
    private NotificationDialog mThumbsUpDialog;
    public static final String ACTION_ALARM_BELL = "com.umeox.moto.intent.action.ACTION_ALARM_BELL";
    private boolean idleFragmentIsHome = true;

    private boolean isMainTipsDialogShow;

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == MSG_SEND_EVEN_BUS) {
                EventBus.getDefault().post(new PrayerTimeListFragmentVisibleEvent());
            }
            return false;
        }
    });

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean("isUserInputEnabled", idleFragmentIsHome);
        outState.putBoolean("isMainTipsDialogShow", isMainTipsDialogShow);
    }

    @Override
    protected void onPostCreate(@Nullable Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        if (savedInstanceState != null) {
            return;
        }

        mPager.postDelayed(() -> {
            try {
                Logger.e(TAG, "开始获取deviceConfig...");
                PushApiClientProxy.fetchBinder().deviceConfig();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }, 3000);

        mPager.postDelayed(() -> runOnUiThread(() -> {
            int tipsNo;
            if (!NetUtils.hasSimCard()) { //无SIM卡
                if (!NetUtils.isWifiEnabled()) { //WIFI关闭
                    tipsNo = 2;
                } else {
                    if (NetUtils.isWifiConnected()) {
                        tipsNo = 3;
                    } else {
                        tipsNo = 4;
                    }
                }
            } else {
                tipsNo = 1;
            }
            Logger.e(TAG, " tipsNo = " + tipsNo);
            boolean notShowFlag = CacheImpl.getInstance().get(String.valueOf(tipsNo), false);
            if (!notShowFlag && !isFinishing()) {
                MainTipsDialog mainTipsDialog = new MainTipsDialog(MainActivity.this, tipsNo);
                mainTipsDialog.show();
                isMainTipsDialogShow = true;
            }

        }), 10 * 1000);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (savedInstanceState != null) {
            idleFragmentIsHome = savedInstanceState.getBoolean("isUserInputEnabled", true);
        }
        EventBus.getDefault().register(this);
        isBind = DataProvider.isActivated();
        mHomePagerIndex = isBind ? BIND_HOME_PAGE_INDEX : HOME_PAGE_INDEX;
        Log.d(TAG, "onCreate: " + this);
        final DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        final float density = displayMetrics.density;
        Log.d(TAG, "onCreate density: " + density + " " + displayMetrics.widthPixels + " " + displayMetrics.heightPixels);
        mPager = findViewById(R.id.pager);
        mPagerAdapter = new HomePagerAdapter(this);
        mPager.setOffscreenPageLimit(2);
        mPager.setAdapter(mPagerAdapter);
        mPagerAdapter.setFragments(FragmentFactory.getMainFragments());
        mPager.setCurrentItem(mHomePagerIndex, false);
        mPager.setUserInputEnabled(idleFragmentIsHome);
        mPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                mCurrentPagerPosition = position;
                if (DataProvider.isActivated() && mCurrentPagerPosition == BIND_HOME_PAGE_INDEX - 1) {
                    //优化
                    mHandler.sendEmptyMessageDelayed(MSG_SEND_EVEN_BUS, 1500);
                } else {
                    mHandler.removeMessages(MSG_SEND_EVEN_BUS);
                }
                //mPager.setUserInputEnabled(position != mPagerAdapter.getItemCount() - 1);
            }
        });

        registerClassModeReceiver();
        mForbidPeriodNow = DataProvider.inForbidPeriodNow();
        if (isBind && mForbidPeriodNow) {
            showClassModeDialog();
        }
    }

    public static void launchApp(String pkg, String cls, Context context) {
        Intent intent = new Intent();
        intent.setClassName(pkg, cls);
        context.startActivity(intent);
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {

        if (ev.getAction() == MotionEvent.ACTION_DOWN) {

            if (mForbidPeriodNow) {
                if (dialogShowing(mClassModeDialog)) {
                    return false;
                }

                showClassModeDialog();
                return true;
            }
        }
        return super.dispatchTouchEvent(ev);
    }


    private void showClassModeDialog() {
        if (dialogShowing(mClassModeDialog)) {
            return;
        }
        mClassModeDialog = NotificationDialog.create(MainActivity.this, 0)
                .icon(R.drawable.ic_reminder_class_mode)
                .message(getString(R.string.class_mode_str));
        mClassModeDialog.show();

    }


    private boolean dialogShowing(MainDialogInterface dialog) {

        return dialog != null && dialog.isShowing();
    }

    private void registerClassModeReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        //开启上课模式
        intentFilter.addAction(Constants.ACTION_ENABLE_FEATURES);
        //取消上课模式
        intentFilter.addAction(Constants.ACTION_DISABLE_FEATURES);
        intentFilter.addAction(Constants.ACTION_UNBIND);
        intentFilter.addAction(Constants.ACTION_ACTIVATION);

        intentFilter.addAction(Constants.ACTION_VOLUME_VOICE_CALL);
        intentFilter.addAction(Intent.ACTION_BATTERY_LOW);
        intentFilter.addAction(Intent.ACTION_LOCALE_CHANGED);
        intentFilter.addAction(ACTION_OUT_CALL_CONNETCTED);
        intentFilter.addAction(Intent.ACTION_POWER_CONNECTED);
        intentFilter.addAction(Constants.ACTION_REFRESH_WALLPAPERS);
        intentFilter.addAction(ACTION_ALARM_BELL);
        intentFilter.addAction(ACTION_THUMBS_UP);
        registerReceiver(mClassModeReceiver, intentFilter);


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Logger.d(TAG, "onDestroy: " + this);
        EventBus.getDefault().unregister(this);
        if (mClassModeReceiver != null) {
            unregisterReceiver(mClassModeReceiver);
            mClassModeReceiver = null;
        }

    }

    @Override
    protected void registerUnbindAndDisableReceiver(boolean register) {

    }

    @Subscribe
    public void onScrollToPager(HorizontalScrollToPagerEvent event) {
        mPager.setCurrentItem(event.pagerIndex, false);
    }

    @Override
    public void onBackPressed() {
        Logger.e("idleFragmentIsHome=" + idleFragmentIsHome);
        if (mPager.getCurrentItem() != mHomePagerIndex) {
            mPager.setCurrentItem(mHomePagerIndex, true);
        } else if (idleFragmentIsHome) {
//            SystemUtils.goToSleep(MainActivity.this);
        }

        EventBus.getDefault().post(new ScrollToPagerEvent(1));

    }

    public void setPagingEnabled(boolean enabled) {
        mPager.setUserInputEnabled(enabled);
    }

    public boolean isUserInputEnabled() {
        return mPager.isUserInputEnabled();
    }

    public void setIdleFragmentIsHome(boolean b) {
        idleFragmentIsHome = b;

    }

    public boolean idleFragmentIsHome() {
        return idleFragmentIsHome;
    }


    @Override
    public void onLowMemory() {
        super.onLowMemory();
        Log.w(TAG, "onLowMemory: " + this);
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        Log.w(TAG, "onTrimMemory level:" + level);
    }


    private class ClassModeReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            final String action = intent.getAction();

            if (action == null) {
                return;
            }
            Log.d(TAG, "ClassModeReceiver: " + action);
            switch (action) {
                case ACTION_ALARM_BELL:
                    Intent intentChallenge = new Intent(MainActivity.this, ChallengeTriggerActivity.class);
                    intentChallenge.putExtra(EXTRA_CHALLENGE_ID, intent.getLongExtra(EXTRA_CHALLENGE_ID, 0));
                    context.startActivity(intentChallenge);
                    break;
                case Constants.ACTION_ENABLE_FEATURES:
                    mForbidPeriodNow = true;
                    if (isBind && DataProvider.inForbidPeriodNow()) {
                        mPager.setCurrentItem(BIND_HOME_PAGE_INDEX, true);
                        EventBus.getDefault().post(new ScrollToPagerEvent(1));
                        if (dialogShowing(mClassModeDialog)) {
                            return;
                        }
                        showClassModeDialog();
                    }
                    break;
                case Constants.ACTION_DISABLE_FEATURES:

                    mForbidPeriodNow = false;
                    if (mClassModeDialog != null) {
                        mClassModeDialog.dismiss();
                    }
                    break;
                case Constants.ACTION_UNBIND:
                    isBind = false;
                    mHomePagerIndex = HOME_PAGE_INDEX;
                    final List<Fragment> mainFragments = FragmentFactory.getMainFragments();
                    final Fragment fragment = mainFragments.get(0);
                    final Bundle arguments = fragment.getArguments();
                    if (arguments != null) {
                        arguments.putInt(KEY_UNBIND, UNBIND_RESTART);
                    }
                    mPagerAdapter.setFragments(mainFragments);
                    if (mPager.getCurrentItem() != mHomePagerIndex) {
                        mPager.setCurrentItem(mHomePagerIndex, true);
                    }
                    EventBus.getDefault().postSticky(new DeviceStatusChangedEvent(DeviceStatusChangedEvent.UNBOUND));
                    EventBus.getDefault().post(new NotificationManagerEvent(0));
                    NotificationDialog unbindDialog = NotificationDialog.create(MainActivity.this, 0)
                            .icon(R.drawable.ic_reminder_unbound)
                            .message(getString(R.string.device_unbind_str));
                    unbindDialog.show();

                    break;
                case Constants.ACTION_ACTIVATION:
                    isBind = true;
                    mHomePagerIndex = BIND_HOME_PAGE_INDEX;
                    mPagerAdapter.setFragments(FragmentFactory.getMainFragments());
                    if (mPager.getCurrentItem() != mHomePagerIndex) {
                        mPager.setCurrentItem(mHomePagerIndex, true);
                    }
                    EventBus.getDefault().postSticky(new DeviceStatusChangedEvent(DeviceStatusChangedEvent.BIND));
                    break;

                case Constants.ACTION_VOLUME_VOICE_CALL:
                    final int volume = intent.getIntExtra(Constants.ACTION_VOLUME_VOICE_CALL, 0);
                    CacheImpl.getInstance().put(CacheImpl.KEY_VOLUME_VOICE_CALL, volume);
                    break;
                case ACTION_OUT_CALL_CONNETCTED:
                    AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
                    int mCallCurrentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
                    final int callVolume = CacheImpl.getInstance().get(CacheImpl.KEY_VOLUME_VOICE_CALL, mCallCurrentVolume);
                    mAudioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, callVolume, AudioManager.USE_DEFAULT_STREAM_TYPE);
                    break;

                case Intent.ACTION_BATTERY_LOW:

                    if (mBatteryLowDialog != null && mBatteryLowDialog.isShowing()) {
                        return;
                    }
                    mBatteryLowDialog = NotificationDialog.create(MainActivity.this, 0)
                            .icon(R.drawable.ic_reminder_battery_low)
                            .message(getString(R.string.battery_low_str));
                    mBatteryLowDialog.show();
                    break;

                case ACTION_BACK:
                    break;
                case Intent.ACTION_LOCALE_CHANGED:
                    EventBus.getDefault().post(new LocaleChangedEvent());
                    break;

                case Intent.ACTION_POWER_CONNECTED:
                    Intent chargeIntent = new Intent(MainActivity.this, ChargingActivity.class);
                    chargeIntent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
                    startActivity(chargeIntent);
                    break;
                case Constants.ACTION_REFRESH_WALLPAPERS:
                    EventBus.getDefault().post(new CustomWallpaperChangedEvent());
                    break;
                case Constants.ACTION_THUMBS_UP:
                    if (mThumbsUpDialog != null && mThumbsUpDialog.isShowing()) {
                        return;
                    }
                    mThumbsUpDialog = NotificationDialog.create(MainActivity.this, 0)
                            .icon(R.drawable.ic_thumbs_up)
                            .message(getString(R.string.thumbs_up_tip));
                    mThumbsUpDialog.show();
                    break;
            }
        }

    }
}
